﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PagedList;
using LKVService;
using LKVMLMLib;
using System.Security.Cryptography;
using System.Text;
using LKVMLMADMIN.Models;
using PinService.Lib;
namespace LKVMLMADMIN.Controllers
{
    public class UserController : Controller
    {
        public static string MD5Hash(string text)
        {
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            md5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(text));
            byte[] result = md5.Hash;
            StringBuilder strBuilder = new StringBuilder();
            for (int i = 0; i < result.Length; i++)
            {
                strBuilder.Append(result[i].ToString("x2"));
            }

            return strBuilder.ToString();
        }
        [AllowAnonymous]
        public ActionResult ListUser(int page = 1, string SearchText = "", string SearchType = "", string Groupid ="",string notice = "")
        {
            if (Session["User"] != null)
            {
                var Listuser= new List<Userloadata>();
                int count = 0;
                var user = Session["User"] as LKVMLMLib.UserProfile;
                
                var db = new LKVService.User();
                //var nguoibt = db.findUserById((int)user.Parent_ID);

                var _lb1 = db.getListGroup().Select(s => new { value = s.GroupName, text = s.GroupName }).ToList();
                _lb1.Insert(0, new { value = "", text = "Chọn Nhóm" });            
                var _model = db.getListUserWithConditionPaging(SearchType, SearchText, Groupid,(page-1)*100,100);           
                if(SearchText=="" && SearchType==""|| Groupid=="")
                {
                    var ListUS = db.getListUserWithConditionPaging(SearchType, SearchText, "Chọn Nhóm", (page - 1) * 100, 100);
                    Listuser = ListUS.Item2.ToList();
                    count = ListUS.Item1;
                }
                else
                {
                    Listuser = _model.Item2.ToList();
                    count = _model.Item1;
                }         
                var ListGroup = db.getListGroup();
                var ListGroupName = new List<string>();
                var ListGroupId = new List<int>();
                foreach(var i in ListGroup)
                {
                    var findgroup = db.findGroupById(i.GroupID);
                    ListGroupName.Add(findgroup.GroupName);
                    ListGroupId.Add(findgroup.GroupID);
                }
                ViewBag.groupName = _lb1;
                ViewBag.groupID = ListGroupId;

                #region Add Get Parent Name Tructiep definition

             
                

                #endregion

                ViewBag.ListUser = Listuser;
                int[] myArray = Enumerable.Repeat(-1, count).ToArray();
                ViewBag.Notice = notice;
                return View(myArray.ToPagedList(page, 100));
            }
            else
                return RedirectToAction("Login", "Account");
        }
        [AllowAnonymous]
        public ActionResult AddUserProfile(Models.RegisterModel model, string LR = "Left", int User = 0, int Groupid = 0, string Sex = "", string FullName = "", string SoCmnd = "", int  Name_IDParent = 0, int Name_IDBinary = 0, string pass = "", string email = "", string Username="")
        {
            var db = new LKVService.User();
            var configParent = db.getConfigTree();
            if (configParent.Option_1 == true)
            {
                ViewBag.SysTree = "1";
            }
            if (configParent.Option_2 == true)
            {
                ViewBag.BinaryTree = "2";
            }
            var ListUser = db.getListUser().Select(s => new { value = s.UserId, text = s.UserName }).ToList();
            ListUser.Insert(0, new { value = 0, text = "Chọn Mã" });
            ViewBag.username = ListUser;
            var groupDefault = db.getListGroup().Where(w => w.Default == true).FirstOrDefault();  
            var _lb1 = db.getListGroup().Where(w=>w.GroupID!=groupDefault.GroupID).Select(s => new { value = s.GroupID, text = s.GroupName }).ToList();
            _lb1.Insert(0, new { value = groupDefault.GroupID, text = groupDefault.GroupName });                
            ViewBag.groupName1 = _lb1;
            if (Username != "")
            {
                var usernn = db.findUserByUserName(Username);
                if (usernn != null)
                {
                    return RedirectToAction("AddUserProfile", "User", new { notice = "Username này đã tồn tại!" });
                }  
            }                                           
                UserProfile UserNew = new UserProfile();
                UserNew.UserName = Username;
                UserNew.GruopID = Groupid;             
                UserNew.Password = MD5Hash(pass);
                UserNew.p = pass;                           
                UserNew.CreateDate = DateTime.Now;
                UserNew.SOCMND = SoCmnd;
                UserNew.SCMNDCUAVOHOACCHONG = model.SoCMNDVOHOACCHONG;
                UserNew.Status = false;
                UserNew.HoanVon = 0;
                UserNew.Level = 0;
                UserNew.QUOCGIA = model.QUOCGIA;
                UserNew.DIACHI = model.DiaChi;
                UserNew.EMAIL = email;
                UserNew.GIOITINH = Sex;
                UserNew.HOTENVOHOACCHONG = model.HoTenVoHoacChong;
                UserNew.MSTCANHAN = model.MSTCANHAN;
                UserNew.NGAYCAP = Convert.ToDateTime(model.NGAYCAP);
                UserNew.NGAYSINH = Convert.ToDateTime(model.NgaySinh);
                UserNew.THANHPHO = model.THANHPHO;
                UserNew.NOICAP = model.NOICAP;
                UserNew.NOISINH = model.NOISINH;
                UserNew.HOTEN = FullName;
                UserNew.SDTNHARIENG = model.SDTNHARIENG;
                UserNew.SDTNOILAMVIEC = model.SDTNOILAMVIEC;
                if (Name_IDParent != 0 && configParent.Option_1 == true)
                 {
                     var ParentId = db.findUserById(Name_IDParent);
                     if (ParentId != null)
                         UserNew.Parent_ID = ParentId.UserId;
                 }

                if (Name_IDBinary != 0 && configParent.Option_2 == true)
                 {
                     var BinaryId = db.findUserById(Name_IDBinary);
                     if (BinaryId != null)
                         UserNew.ParentB_ID = BinaryId.UserId;
                }       
      
                UserNew.SoTaiKhoan = model.SoTaiKhoan;
                UserNew.NganHang = model.NganHang;
                if(Username!="" && pass!="")
                {
                    if (configParent.Option_2 == true && UserNew.ParentB_ID == null && UserNew.Parent_ID != null)
                    {
                       return RedirectToAction("AddUserProfile", "User", new { notice = "Chưa điền mã chỉ định!" });                                                                         
                    }
                    if (UserNew.Parent_ID == null && configParent.Option_1 == true && UserNew.ParentB_ID != null)
                    {
                        return RedirectToAction("AddUserProfile", "User", new { notice = "Chưa điền mã bảo trợ!" });  
                    }
                    var rs = db.AddUserWithPackge(UserNew, LR, User, Convert.ToInt32(model.soluongma));
                    if (rs != 0 )
                    {
                        return RedirectToAction("ListUser", "User", new { notice = "Bạn đã thêm thành công!" });
                    }
                    else
                        return RedirectToAction("AddUserProfile", "User", new { notice = "Thêm không thành công!" });
                }
                return View();   
        }
        [AllowAnonymous]
        public ActionResult Group()
        {
            if (Session["User"] != null)
            {
                var db = new LKVService.User();
                var ListGroup = db.getListGroup();
                ViewBag.group = ListGroup;              
                return View();
            }
            else
                return RedirectToAction("Login", "Account");
        }
         [AllowAnonymous]
        public ActionResult DeleteGroup(int id =0)
        {
            if (Session["User"] != null)
            { 
                if(id!=0)
                {
                    var db = new LKVService.User();
                    db.RemoveGroup(id);
                    return RedirectToAction("Group", "User");
                }
                return View();
            }
            else
                return RedirectToAction("Login", "Account");
        }

        [AllowAnonymous]
        public ActionResult Addgroup(string GroupName="")
        {
            var db = new LKVService.User();
            if (GroupName != "")
            {
                var DKName = db.findGroupByGroupName(GroupName);                 
                if(DKName==null)
                {
                    Group c = new Group();
                    c.GroupName = GroupName;
                    db.Addgroup(c);
                    return RedirectToAction("Group", "User");                
                }
                return RedirectToAction("Group", "User");       
            }
            else
                return View();
        }
        [AllowAnonymous]
        public ActionResult groupDetail(GroupModel model, int GrId = 0)
        {
            var db = new LKVService.User();
            var group = db.findGroupById(GrId);
            model.GroupName = group.GroupName;
            model.ID = group.GroupID;
            return View(model);
        }
        [AllowAnonymous]
        public ActionResult AdddefaultGroup(int dfid = 0)
        {
            var extension =new LKVService.User();
            var check = extension.getListGroup().Where(w => w.Default == true).Count();
            if(check==0)
            {
                var grchoose = extension.findGroupById(dfid);
                grchoose.Default = true;
                extension.UpdateGroup(grchoose);
            }
           if(check==1)
           {
               var groupDefefault = extension.getListGroup().Where(w => w.Default == true).FirstOrDefault();
               groupDefefault.Default = false;
               extension.UpdateGroup(groupDefefault);
               var grchoose = extension.findGroupById(dfid);
               grchoose.Default = true;
               extension.UpdateGroup(grchoose);
           }
            return RedirectToAction("Group", "User");               
        }
        [HttpPost]
        [AllowAnonymous]
        public ActionResult groupDetail(GroupModel model)
        {
            var db = new LKVService.User();
            var groupupdate = db.findGroupById(model.ID);
            groupupdate.GroupName=model.GroupName;
            var check= db.UpdateGroup(groupupdate);
            if(check==1)           
                return RedirectToAction("Group", "User");       
            else           
            return View(model);
        }
        public ActionResult SystemTree()
        {
            if (Session["User"] != null)
            {
                return View();
            }
            else
                return RedirectToAction("Login", "Account");
        }
        public ActionResult BinaryTree()
        {
            if (Session["User"] != null)
            {             
                return View();
            }
            else
                return RedirectToAction("Login", "Account");
        }
        public JsonResult showTreeSys()
        {
            var db = new LKVService.User();
            var _user = Session["User"] as LKVMLMLib.UserProfile;
            var _data = new List<UserProfile>();
            string _nodeParent = string.Empty;
            _data = db.getTreeParent(_user.UserName).ToList();
            _data.ForEach(x =>
            {
                if (x.UserId == _user.UserId)
                {
                    x.Parent_ID = null;
                }
            });
            List<JsTreeModel> doc = _data.Select(x => new JsTreeModel()
            {
                id = x.UserId.ToString(),
                parent = x.Parent_ID != null ? x.Parent_ID.ToString() : "#",
                text = x.UserName,//_rootLevel == countLevel(x.FamilyBinary)? x.UserName + " (0)" : x.UserName +" (" + (countLevel(x.FamilyBinary)-_rootLevel)+")",
                icon = x.Status == true ? "fa fa-user active" : "fa fa-user unactive",
                state = new StateTree { opened = true, disabled = false, selected = false }
            }).ToList();
            return Json(doc.ToArray(), JsonRequestBehavior.AllowGet);
        }
        public JsonResult showBinaryTree()
        {
            var db = new LKVService.User();
            var _user = Session["User"] as LKVMLMLib.UserProfile;
            string _nodeParent = string.Empty;
            var _data = new List<UserProfile>();
            _user.ParentB_ID = null;
            _data = db.getTreeBinary(_user.UserName).ToList();
            _data.ForEach(x =>
            {
                if (x.UserId == _user.UserId)
                {
                    x.ParentB_ID = null;
                }
            });
            List<JsTreeModel> doc = _data.Select(x => new JsTreeModel()
            {
                id = x.UserId.ToString(),
                parent = x.ParentB_ID != null ? x.ParentB_ID.ToString() : "#",
                text = x.UserName,//_rootLevel == countLevel(x.FamilyBinary)? x.UserName + " (0)" : x.UserName +" (" + (countLevel(x.FamilyBinary)-_rootLevel)+")",
                icon = x.Status == true ? "fa fa-user active" : "fa fa-user unactive",
                state = new StateTree { opened = true, disabled = false, selected = false },
                children = new string[] { }
            }).ToList();
            return Json(doc.ToArray(), JsonRequestBehavior.AllowGet);
        }
        public ActionResult Delete(string userName)
        {
            if (Session["User"] != null)
            {
                string _result = null;
                var db = new LKVService.User();
                var userDel = db.findUserByUserName(userName);
                _result = db._delUser(userDel.UserId);
               return RedirectToAction("ListUser", "User", new { notice  = _result});
            }
            else
                return RedirectToAction("Login", "Account");
        }
        public ActionResult Edit(string userName = "", string notice = "")
        {
            if (Session["User"] != null)
            {
                if(String.IsNullOrEmpty(userName))
                    return RedirectToAction("Index", "Home");
                var db = new LKVService.User();
                var model = db.findUserByUserName(userName);
                var _dropdownData = getDataDropDown();
                var _dropdownDataParent = getDataDropDownParent();
                ViewBag.Gender = _dropdownData.Item1.Select(s => new SelectListItem
                {
                    Text = s.TextGender,
                    Value = s.ValueGender,
                    Selected = model.GIOITINH == s.TextGender ? true : false
                }).AsEnumerable();
                ViewBag.Group = _dropdownData.Item2.Select(s => new SelectListItem
                {
                    Text = s.TextGroup,
                    Value = ((int)s.ValueGroup).ToString(),
                    Selected = model.GruopID == s.ValueGroup ? true : false
                }).AsEnumerable();
                ViewBag.Position = _dropdownData.Item3.Select(s => new SelectListItem
                {
                    Text = s.TextPosition,
                    Value = s.ValuePosition,
                    Selected = returnSelected(model)
                }).AsEnumerable();
                ViewBag.ParentUser = _dropdownDataParent.Item1.Select(s => new SelectListItem
                {
                    Text = s.TextParent,
                    Value = s.ValueParent.ToString(),
                    Selected = model.Parent_ID == s.ValueParent ? true : false
                });
                ViewBag.BinaryUser = _dropdownDataParent.Item2.Select(s => new SelectListItem
                {
                    Text = s.TextBinary,
                    Value = s.ValueBinary.ToString(),
                    Selected = model.ParentB_ID == s.ValueBinary ? true : false
                }); 
                ViewBag.Notice = notice;
                var configParent = db.getConfigTree();
                if (configParent.Option_1 == true)
                {
                    ViewBag.SysTree = "1";
                }
                if (configParent.Option_2 == true)
                {
                    ViewBag.BinaryTree = "2";
                }
                return View(model);
            }
            else
                return RedirectToAction("Index", "Home");
        }
        [HttpPost]
        public ActionResult Edit(UserProfile user, string LR ="")
        {
            if (Session["User"] != null)
            {
                var db = new LKVService.User();
                var rs = db.UpdateUser(user, LR);
                string notice = "";
                switch (rs)
                {
                    case 0:
                        notice = "User Edit không tồn tại !";
                        break;
                    case 1:
                        notice = "Không thể thay đổi từ cha xuống con !";
                        break;
                    case 2:
                        notice = "Thành viên này đã đủ 2 con !";
                        break;
                    case 3:
                        notice = "Không thể di chuyển root !";
                        break;
                    case 4:
                        notice = "Left/Right không trống !";
                        break;
                    default:
                        notice = "Thay đổi dữ liệu thành công !";
                        break;
                }
                return RedirectToAction("Edit", "User", new { userName = user.UserName, notice = notice });
            }
            else
                return RedirectToAction("Home", "Index");
        }
        public Tuple<List<GenderUser>, List<GroupUser>, List<PositionUser>> getDataDropDown()
        {
            var db = new LKVService.User();
            var _gender = new List<GenderUser>();
            var _group = new List<GroupUser>();
            var _position = new List<PositionUser>();
            _gender.Add(new GenderUser{ ValueGender = "Nam",TextGender = "Nam"});
            _gender.Add(new GenderUser { ValueGender = "Nữ", TextGender = "Nữ" });
            db.getListGroup().ToList().ForEach(s => {
                _group.Add(new GroupUser
                {
                    TextGroup = s.GroupName,
                    ValueGroup = s.GroupID
                });
                });
            _position.Add(new PositionUser { ValuePosition =  "Left",TextPosition ="Left" });
            _position.Add(new PositionUser { ValuePosition = "Right", TextPosition = "Right" });
            return new Tuple<List<GenderUser>, List<GroupUser>, List<PositionUser>>(_gender, _group, _position);
        }

        public Tuple<List<ParentUser>,List<BinaryUser>>getDataDropDownParent()
        {
            var db = new LKVService.User();
            var _parent = new List<ParentUser>();
            _parent.Add(new ParentUser{TextParent="Please choose",ValueParent=null});
            var _binary = new List<BinaryUser>();
            _binary.Add(new BinaryUser { TextBinary = "Please choose", ValueBinary = null });
            db.GetlistParentforcombobox().ToList().ForEach(s =>
            {
                _parent.Add(new ParentUser
                {
                    TextParent = s.username,
                    ValueParent = (int)s.Userid
                });
            });
            db.GetlistBinaryidforcombobox().ToList().ForEach(s =>
            {
                _binary.Add(new BinaryUser
                {
                    TextBinary = s.username,
                    ValueBinary = (int)s.Userid
                });
            });
            return new Tuple<List<ParentUser>, List<BinaryUser>>(_parent, _binary);
        }
        public ActionResult ChangepassForUser(RegisterModel model, string userName = "")
        {
            var extension =new LKVService.User();
            var userchoose = extension.findUserByUserName(userName);
            model.UserName = userchoose.UserName;
            return View();
        }
        [HttpPost]
        public ActionResult ChangepassForUser(RegisterModel model, string Newpass = "", string a = "")
        {
            var extension = new LKVService.User();
            if (model.UserName != null && Newpass != "")
            {
                var userchoose = extension.findUserByUserName(model.UserName);
                string _newMd5 = MD5Hash(Newpass);
                userchoose.p = Newpass.Trim();
                userchoose.Password = _newMd5;
                var check = extension.changPassword(userchoose);
                if (check == 1)
                    return RedirectToAction("ListUser", "User");
                else
                    return View();
            }
            else
                return View();
        }
        public ActionResult UserConfig( PrefixModel model)
        {
            var extension = new LKVService.User();         
            bool tusinh;
            bool tugo;
            var UserConfig = extension.ChooseConfigUser();
            if (UserConfig.AGUsername == true)
               tusinh = true;
            else
               tusinh = false;
            if (UserConfig.AGUsername == false)
                tugo = true;
            else
                tugo = false;
            model.prefix = UserConfig.Suffix;
            ViewBag.tusinh = tusinh;
            ViewBag.tugo = tugo;
            return View(model);
        }
        [HttpPost]
        public ActionResult UserConfig( string id, string val, string prefix="")
        {          
                bool a;
                if (val == "on")
                    a = true;
                else
                    a = false;
                var extenssion = new LKVService.User();            
                var UpdateUserConfig = extenssion.ChooseConfigUser();
                if (id == "CG_1")
                    UpdateUserConfig.AGUsername = a;
                if (id == "CG_2")
                    UpdateUserConfig.AGUsername = a;
                if (prefix!="")
                {
                    UpdateUserConfig.Suffix = prefix;
                }       
                extenssion.UpdateUserConfig(UpdateUserConfig);
                return RedirectToAction("UserConfig", "User");                    
        }
        public bool returnSelected(UserProfile userLoad)
        {
            var db = new LKVService.User();
            bool kq = false;
            var configParent = db.getConfigTree();
            if (configParent.Option_2 == true)
            {
                var parentB = db.findUserById((int)userLoad.ParentB_ID);
                if (parentB != null && parentB.Right != null && parentB.Right == userLoad.UserId)
                    kq = true;
            }            
            return kq;
        }
        public ActionResult Disable(int userid=0)
        {
            if (Session["User"] == null)
                return RedirectToAction("Login", "Account");
            if(userid!=0)
            {
            var extension = new LKVService.User();
            var userchooe = extension.findUserById(userid);
            userchooe.Status = false;
            extension.UpdateUser(userchooe);
            }
             return RedirectToAction("ListUser", "User");
        }

        public ActionResult Enable(int userid = 0)
        {
            if (Session["User"] == null)
                return RedirectToAction("Login", "Account");
                
            if(userid!=0)
            {
            var extension = new LKVService.User();
            var userchooe = extension.findUserById(userid);
            userchooe.Status = true;
            extension.UpdateUser(userchooe);
            }
             return RedirectToAction("ListUser", "User");
        }
        
        [HttpGet]
        public ActionResult ChangeBanks(string UserName = "")
        {
            var model = new ChangeBankView();
            if (UserName != "")
            {
                if (Session["User"] != null)
                {
                    var transactionService = new LKVService.Transaction();
                    var listPayment = transactionService.GetPaymentMethods();
                    var userContext = new LKVService.User();
                    var userChange = userContext.findUserByUserName(UserName);
                    List<SelectListItem> DropDownListPayment = new List<SelectListItem>();
                    foreach (var item in listPayment)
                    {
                        DropDownListPayment.Add(new SelectListItem() { Text = item.Name, Value = item.Id.ToString() });
                    }
                    if (userChange != null)
                    {
                        model.ListPayment = DropDownListPayment;
                        model.UserId = userChange.UserId;
                        model.UserName = userChange.UserName;
                        var AccPerfectMoney = transactionService.getAccountPerfectMoney(userChange.UserId);
                        if(AccPerfectMoney!=null){
                             model.Payer = AccPerfectMoney.Payer;
                        }
                        else
                        {
                            model.Payer = "";
                        }                       
                    }
                    //DropDownListPayment;                    
                    return View(model);
                }
            }
            return RedirectToAction("Login", "Account");
        }
        [HttpPost]
        public ActionResult ChangeBanks(ChangeBankView form)
        {
            var UserService = new LKVService.User();
            if (form.PaymentId == 1)
            {
                UserService.changeBanks(form.UserId,form.Payer);
                ModelState.AddModelError("", "Cập nhật tài khoản prefect money thành công");
            }
            if (form.PaymentId == 4)
            {
                if (UserService.changeBankQueProject(form.UserId, form.Payer)){

                    ModelState.AddModelError("", "Update Bank sussecc");
                    return RedirectToAction("ListUser","User");
                }
                else
                {
                    ModelState.AddModelError("", "Update Bank Error!");
                    return View();
                }
            }
            if (form.PaymentId == 2)
            {

                return RedirectToAction("ListUser", "User");
                
            }
            return RedirectToAction("ListUser","User");
        }
       
    }
    public class ChangeBankView
    {
        public List<SelectListItem> ListPayment { get; set; }
        public int UserId { get; set; }
        public string UserName { get; set; }
        public string Payer { get; set; }
        public int PaymentId { get; set; }
    }  
}
